import { Pagination } from "react-bootstrap";


/**
 * 翻页组件
 * @param {object} props
 * @param {number} props.currentPage
 * @param {number} props.totalPages
 * @param {(number) => {}} props.gotoPageCallback
 */
function PaginationBar({ currentPage, totalPages, gotoPageCallback}) {
    let items = [];
    // 当前页码靠前：只显示后引号
    if (currentPage <= 5) {
        for (let i = 0; i < Math.min(7, totalPages); i++)
            items.push(<Pagination.Item key={i} active={i === currentPage} onClick={() => gotoPageCallback(i)}>{i + 1}</Pagination.Item>);
        if (totalPages > 7) {
            items.push(<Pagination.Ellipsis key={8} />);
            items.push(<Pagination.Item key={9} active={currentPage === totalPages - 1} onClick={() => gotoPageCallback(totalPages - 1)}>{totalPages}</Pagination.Item>);
        }
    }
    // 当前页码靠后：只显示前引号
    else if (currentPage >= totalPages - 5) {
        items.push(<Pagination.Item key={0} active={0 === currentPage} onClick={() => gotoPageCallback(0)}>1</Pagination.Item>);
        items.push(<Pagination.Ellipsis key={1} />);
        for (let i = totalPages - 7; i < totalPages; i++)
            items.push(<Pagination.Item key={i} active={i === currentPage} onClick={() => gotoPageCallback(i)}>{i + 1}</Pagination.Item>);
    }
    // 当前页码居中：显示前后各两个引号
    else {
        items.push(<Pagination.Item key={0} active={0 === currentPage} onClick={() => gotoPageCallback(0)}>1</Pagination.Item>);
        items.push(<Pagination.Ellipsis key="e1" />);
        for (let i = currentPage - 2; i <= currentPage + 2; i++)
            items.push(<Pagination.Item key={i} active={i === currentPage} onClick={() => gotoPageCallback(i)}>{i + 1}</Pagination.Item>);
        items.push(<Pagination.Ellipsis key="e2" />);
        items.push(<Pagination.Item key="last" active={totalPages - 1 === currentPage} onClick={() => gotoPageCallback(totalPages - 1)}>{totalPages}</Pagination.Item>);
    }


    return (
        <Pagination className="justify-content-center">
            <Pagination.Prev disabled={currentPage === 0} onClick={() => gotoPageCallback(currentPage - 1)} />
            {items}
            <Pagination.Next disabled={currentPage === totalPages - 1} onClick={() => gotoPageCallback(currentPage + 1)} />
        </Pagination>
    );
}

export default PaginationBar;